// import $ from '../lib/jquery';
import Hooks from '../common/hooks';
import tools from '../common/tools';
import React from 'react';
import ReactDOM from 'react-dom';
import Charter from './charts/charts';
import Saver from './charts/save';

class Grouper {
    constructor(groups,sheeter){
        let that=this;
        this.groups=groups||{};
        this.sheeter=sheeter;

        this.chartercontrol=new Hooks();
        this.chartercontrol.addHook('callback',function(data){
            let params=data.params;
            if(params.data){
                if(params.evt==='savegroup'){
                    if(params.data.id){
                        that.addItem(params.data.id,params.data);
                        sheeter.saveChart({evt:'savegroup',data:params.data});
                    }
                }else if(params.evt==='savechart'){
                     that.savercontrol.dispatch('show',{state:{
                         id:tools.uuid(),
                         name:'',
                         desc:'',
                         data:JSON.stringify(params.data)
                     }})
                }
            }
        });

        this.savercontrol=new Hooks();
        this.savercontrol.addHook('callback',function(data){
            let params=data.params;
            sheeter.saveChart(params);
        });

        ReactDOM.render((
            <div>
            <Saver control={this.savercontrol} />
            <Charter control={this.chartercontrol} sheets={this.sheeter}/>
            </div>
        ),document.querySelector('#modal_el'));
        
        this.init();
    }
    refreshChart(){
        this.chartercontrol.dispatch('refresh');
    }
    init(){
  		this.initView();
  		this.bindEvent();
  	}
  	bindEvent(){
  		var that=this;
        $(document).on('click', '.group-opts', function(event) {
            event.preventDefault();
            /* Act on the event */
            var gid=$(this).data('gid');
            var group=that.getItem(gid)
                    ,name=group.name
                    ,type=group.type;
            that.chartercontrol.dispatch('show',group);
        });
  	}
  	initView(){
  		var groupEls=[];
  		$('.group-item').remove();
  		for(var i in this.groups){
  			groupEls.push(this.generateGroupEl(this.groups[i]));
  		}
  		$('.htBorders').append(groupEls.join(''));
  	}
  	generateGroupEl(group){
  		var id=group.id
	  			,name=group.name
	  			,r=group.r
	  			,c=group.c
	  			,lr=group.lr
	  			,lc=group.lc
	  			,type=group.type;

  		var tpl='<div id="{groupid}" class="group-item group-warper" style="{styles}">\
                <span style="width:{width};" class="group-line gtoup-top"></span>\
                <span style="height:{height};left:{width};" class="group-line gtoup-right"></span>\
                <span style="width:{width};top:{height};" class="group-line gtoup-bottom"></span>\
                <span style="height:{height};" class="group-line gtoup-left"></span>\
                <span data-gid="{groupid}" class="group-opts" data-tips="分组: {groupname}"></span>\
              </div>';
      var TDS=this.sheeter.handsontable.getCell(r,c),TDE=this.sheeter.handsontable.getCell(lr,lc);
      if(TDS==undefined||TDE==undefined) return;
      var ps=$(TDS).position(),pe=$(TDE).position();
      var styles='top:'+(ps.top-1)+'px;left:'+(ps.left-1)+'px;'
      		,width=(pe.left+$(TDE).outerWidth()-ps.left)+'px'
          ,height=(pe.top+$(TDE).outerHeight()-ps.top)+'px';
      var groupel=tpl.replace(/\{width\}/ig,width)
      							.replace(/\{height\}/ig,height)
      							.replace(/\{groupname\}/ig,name)
      							.replace(/\{groupid\}/ig,id)
      							.replace(/\{styles\}/ig,styles);
        return groupel;
  	}
  	popup(title,cont,callback){
      var mode='<div class="mode-popup">\
                  <div class="mode-popup-header">\
                    <span class="mode-title">{title}</span>\
                    <span class="mode-tools mode-cancel"><i class="fa fa-close"></i></span>\
                  </div>\
                  <div class="mode-popup-conter">{cont}</div>\
                  <div class="mode-popup-footer">\
                    <span class="mode-btn mode-cancel">取消</span>\
                    <span class="mode-btn mode-ok">确认</span>\
                  </div>\
                </div>',
          modebg='<div class="mode-popup-bg"></div>';
      var title=title||'系统提示',cont=cont||'No Message.';
      var modestr=mode.replace('{title}',title)
                      .replace('{cont}',cont);
      var __modebg=$(modebg).appendTo('body'),
          __mode=$(modestr).appendTo('body');

      __mode.on('click', '.mode-ok', function(event) {
        event.preventDefault();
        if(typeof callback=='function'){
          callback(__mode);
        }
        clear();
      });
      __mode.on('click', '.mode-cancel', function(event) {
        event.preventDefault();
        clear();
      });
      function clear(){
        __modebg.remove();
        __mode.remove();
        __mode=__modebg=null;
      }
  	}
  	reset(groups,sheeter){
        console.log('reset');
  		this.groups=groups||{};
  		this.sheeter=sheeter;
  	}
  	clear(){
        console.log('clear');
	  	this.groups={};
  	}
  	save(){
  		return this.groups;
  	}
  	removeItem(k){
  		delete this.groups[k];
  	}
  	addItem(k,v){
  		this.groups[k]=v;
  	}
  	getItem(k){
  		return this.groups[k];
  	}
  	addGroup(r,c,lr,lc){
  		var id=tools.uuid(),id2=tools.uuid();
        var that=this,
      		tpl='<div class="mode-item">\
      					<div><input class="form-control" id="'+id+'" type="text" placeholder="请输入分组名称"/></div>\
      					<div class="opts-splitline"></div>\
      					<div><select class="form-control" id="'+id2+'">'+this.toOptions()+'</select></div>\
      					</div>';
        this.popup('设置组',tpl,function(mode){
            var name=mode.find('#'+id).val(),gid=mode.find('#'+id).data('gid');
            if(gid==''&&name=='') return;
            gid=gid==undefined?tools.uuid():gid;
            that.addItem(gid,{id:gid,name:name,r:r,c:c,lr:lr,lc:lc,type:null});
            that.initView();
        });
        $('#'+id2).on('change',function(){
            var gid=$(this).val(),gname=$(this).find('option:selected').text();
            if(gid!=""){
                $('#'+id).data('gid',gid).val(gname);
            }else{
                $('#'+id).data('gid','').val('');
            }
        });
  	}
    toOptions(){
        var opts='<option value="">选择已有分组</option>';
        for(var i in this.groups){
            opts+='<option value="'+this.groups[i].id+'">'+this.groups[i].name+'</option>';
        }
        return opts;
    }
}

export default Grouper;